package com.gane.maple.jdbc.routing.component;

import com.gane.maple.jdbc.routing.ClientDataSource;
import com.gane.maple.jdbc.routing.ClientDataSourceContextHolder;
import com.gane.maple.jdbc.routing.annotation.DataSourceRouting;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author maple
 * @date 2021/3/3
 */
@Aspect
@Component
@Slf4j
public class DataSourceRoutingAspect {

    @Around("@annotation(dataSourceRouting)")
    public Object aroundDataSourceRouting(ProceedingJoinPoint joinPoint, DataSourceRouting dataSourceRouting)
            throws Throwable {
        ClientDataSource previousClient = ClientDataSourceContextHolder.getClientDatabase();
        log.warn("Setting clientDatabase {} into DataSourceContext", dataSourceRouting.value());
        ClientDataSourceContextHolder.set(dataSourceRouting.value());

        try {
            return joinPoint.proceed();
        } finally {
            if (previousClient != null) {
                // revert context back to previous state after execute the method
                ClientDataSourceContextHolder.set(previousClient);
            } else {
                // there is no value being set into the context before, just clear the context
                // to prevent memory leak
                ClientDataSourceContextHolder.clear();
            }
        }
    }
}
